package com.ly.sy.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

public class saveObject {
    //    静态常量
    private static final String Point = "oss-cn-shenzhen.aliyuncs.com";
    private static final String AccessKeyId = "LTAI4GAKBF1CTWDEf6kqN7V7";
    private static final String AccessKeySecret = "NsPrj9vxTQO1LAhAo3IiaGSXiSXZdw";
    private static final String BucketName = "edu-linagyu-sy";

/**
 *
 * 文件上传（图片）
 * 这里要用到的是上传文件流
 *
 * **/
    public static String updown(MultipartFile file){
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = Point;
        String accessKeyId = AccessKeyId;
        String accessKeySecret = AccessKeySecret;
        String bucketName = BucketName;
        System.out.println("我来到了oss工具类中");
        System.out.println("获取到的对象："+file);
        try{
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();

            //获取文件名
            String fileName = file.getOriginalFilename();

            //生成一个随机数
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //拼接文件名
            //图片的固定路径
            String imgurl = "Imges/";
            fileName = imgurl+uuid+fileName;

            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();

            //拼接上传到阿里的路径用来返回
            //https://edu-linagyu-sy.oss-cn-shenzhen.aliyuncs.com/Imges/linuxtest.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            return url;

        }catch (Exception e){
            return null;
        }

    }

}
